package cn.huapu.power.energy.controller;

import cn.huapu.power.energy.bean.SysUser;
import cn.huapu.power.energy.bean.vo.LoginVo;
import cn.huapu.power.energy.service.BaseService;
import cn.huapu.power.energy.service.SysUserService;
import cn.huapu.power.energy.util.ObjectHelper;
import cn.huapu.power.energy.util.token.JwtUtil;
import cn.huapu.power.energy.vo.Ret;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @author zhengxiong.jiang
 * @title: LoginController
 * @projectName energy
 * @description: TODO 登录逻辑处理接口
 * @date 2019-5-2410:03
 */
@RestController
@RequestMapping("")
@SessionAttributes("account")
public class LoginController {

    private Log log = LogFactory.getLog(LoginController.class);

    private String errorcount = "errorcount";
  
    @Autowired
    private SysUserService sysUserService;

    /**
    * @Author jzx
    * @Description //TODO 登录逻辑判断
    * @Date 10:10 2019-5-24
    * @Param [userName, password]
    * @return cn.huapu.power.energy.vo.Ret
    **/
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Ret login(@RequestBody LoginVo user, HttpSession session){
//        session.setMaxInactiveInterval(30 * 60);
//        int interval = session.getMaxInactiveInterval();
        log.info("请求参数为:"+user.getUsername()+"*******************************"+user.getPassword());
        Ret r = new Ret();
        int attribute=1;
        if(ObjectHelper.isNotEmpty(session.getAttribute(errorcount))){
            //获取登录失败次数
            attribute = (int)session.getAttribute(errorcount);
            if(attribute>5){
                r.Error("登录次数超过五次,请30分钟后再来登录",attribute);
                return r;
            }
        }
//        PcmUser pcmUser = pcmUserService.queryByNamePs(user.getUsername(),user.getPassword());
        SysUser pcmUser = sysUserService.queryByNamePs(user.getUsername(),user.getPassword());
        if(ObjectHelper.isEmpty(pcmUser)){
            r.Error("登录失败，用户名密码错误",attribute);
            //设置登录次数
            session.setAttribute(errorcount,attribute+1);
        }else{
            session.setAttribute("user",pcmUser);
            //清除登录次数缓存
            session.removeAttribute(errorcount);
            r.OK("登录成功","Bearer:"+JwtUtil.getToken(pcmUser.getUsername(),String.valueOf(pcmUser.getPkid()),String.valueOf(pcmUser.getClientid())));
        }
        return r;
    }
}
